package edu.ptu.zhiyan.controller;

import com.alibaba.fastjson.JSONObject;
import edu.ptu.zhiyan.base.Result;
import edu.ptu.zhiyan.entity.User;
import edu.ptu.zhiyan.service.user.impl.UserServiceImpl;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;


@RestController
//@CrossOrigin(origins = "*",maxAge = 3600)
@RequestMapping("/api")
public class UserController {

    // 注意：这里不需要换成UserService userServiceImpl，
    //      因为接口只是为了继承IService，从而包装service层
    @Resource
    UserServiceImpl userServiceImpl;

    @GetMapping("/query")
    public Result userQuery(@RequestParam("uid") Integer uid){
        User res = userServiceImpl.queryUser(uid);
        if(res==null)
            return Result.fail("查询失败");
        else{
            //
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("username",res.getUsername());
            // 注意，Result的方法携带的参数不同，就代表不同的返回结果
            return Result.ok(jsonObject,"用户查询成功");
        }

    }

    @PostMapping("/login")
    public Result userLogin(@RequestBody User user){
        User res = userServiceImpl.loginUser(user);
        if(res==null)
            return Result.fail("登录失败");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("uid",res.getUid());
        return Result.ok(jsonObject,"登录成功");
    }

    @PostMapping("/register")
    public Result userRegister(@RequestBody User user){
        User res=userServiceImpl.saveUser(user);
        if(res!=null){
            return Result.ok(res,"注册成功");
        }else{
            //System.out.println("注册"+user);
            return Result.fail("注册失败");
        }

    }

    @PostMapping("/remove")
    public Result userRemove(@RequestBody Integer uid){
         if(userServiceImpl.removeUser(uid)){
             return Result.ok("删除成功") ;
         }else{
             return Result.ok("删除失败") ;
         }


    }
}
